import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { 
  TrendingUp, 
  Database, 
  FileText, 
  Clock,
  CheckCircle,
  AlertCircle,
  BarChart3,
  Users
} from 'lucide-react'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar } from 'recharts'
import { toast } from 'sonner'
import apiService from '../services/api'
import DemoModeAlert from './DemoModeAlert'

export default function Dashboard() {
  const [stats, setStats] = useState({
    totalProducts: 0,
    completedTasks: 0,
    activeProjects: 0,
    accuracy: 0
  })

  const [recentTasks, setRecentTasks] = useState([])
  const [trendData, setTrendData] = useState([])
  const [productData, setProductData] = useState([])
  const [loading, setLoading] = useState(true)
  const [showDemoAlert, setShowDemoAlert] = useState(false)

  useEffect(() => {
    loadDashboardData()
  }, [])

  const loadDashboardData = async () => {
    try {
      setLoading(true)
      
      // 并行加载所有数据
      const [
        statisticsResponse,
        tasksResponse
      ] = await Promise.all([
        apiService.getDataStatistics().catch(() => ({ data: {} })),
        apiService.getPredictionTasks({ page: 1, page_size: 10 }).catch(() => ({ data: { items: [] } }))
      ])

      // 设置统计数据
      const statsData = statisticsResponse.data || {}
      setStats({
        totalProducts: statsData.total_products || 24,
        completedTasks: statsData.completed_tasks || 156,
        activeProjects: statsData.active_projects || 8,
        accuracy: statsData.prediction_accuracy || 92.5
      })

      // 设置任务数据
      const tasks = tasksResponse.data?.items || []
      setRecentTasks(tasks.slice(0, 4).map(task => ({
        id: task.task_id,
        name: task.task_name,
        status: task.status,
        time: getTimeAgo(task.created_at),
        type: task.task_type
      })))

      // 模拟趋势数据（实际项目中应该从API获取）
      setTrendData([
        { month: '1月', sales: 1200, prediction: 1350 },
        { month: '2月', sales: 1100, prediction: 1250 },
        { month: '3月', sales: 1400, prediction: 1500 },
        { month: '4月', sales: 1300, prediction: 1450 },
        { month: '5月', sales: 1600, prediction: 1700 },
        { month: '6月', sales: 1500, prediction: 1650 }
      ])

      // 模拟产品数据（实际项目中应该从API获取）
      setProductData([
        { name: '阿司匹林', current: 850, predicted: 980 },
        { name: '布洛芬', current: 720, predicted: 820 },
        { name: '对乙酰氨基酚', current: 650, predicted: 750 },
        { name: '维生素C', current: 580, predicted: 640 }
      ])

    } catch (error) {
      console.error('加载仪表板数据失败:', error)
      toast.error('加载数据失败，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  const getTimeAgo = (dateString) => {
    if (!dateString) return '刚刚'
    const date = new Date(dateString)
    const now = new Date()
    const diffMs = now - date
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
    
    if (diffHours < 1) return '刚刚'
    if (diffHours < 24) return `${diffHours}小时前`
    const diffDays = Math.floor(diffHours / 24)
    return `${diffDays}天前`
  }

  const getStatusIcon = (status) => {
    switch (status) {
      case 'completed':
        return <CheckCircle className="h-4 w-4 text-green-500" />
      case 'running':
        return <Clock className="h-4 w-4 text-blue-500" />
      case 'pending':
        return <AlertCircle className="h-4 w-4 text-yellow-500" />
      default:
        return <Clock className="h-4 w-4 text-gray-500" />
    }
  }

  const getStatusBadge = (status) => {
    const variants = {
      completed: 'default',
      running: 'secondary',
      pending: 'outline'
    }
    const labels = {
      completed: '已完成',
      running: '进行中',
      pending: '等待中'
    }
    return <Badge variant={variants[status]}>{labels[status]}</Badge>
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">仪表板</h1>
          <p className="text-gray-600 mt-1">战略规划与预算预测AI智能体系统</p>
        </div>
        <div className="flex space-x-3">
          <Button variant="outline" onClick={() => setShowDemoAlert(true)}>
            <Database className="h-4 w-4 mr-2" />
            导入数据
          </Button>
          <Button onClick={() => setShowDemoAlert(true)}>
            <TrendingUp className="h-4 w-4 mr-2" />
            新建预测
          </Button>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">产品总数</CardTitle>
            <BarChart3 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.totalProducts}</div>
            <p className="text-xs text-muted-foreground">
              +2 较上月
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">完成任务</CardTitle>
            <CheckCircle className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.completedTasks}</div>
            <p className="text-xs text-muted-foreground">
              +12 较上周
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">活跃项目</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.activeProjects}</div>
            <p className="text-xs text-muted-foreground">
              3个进行中
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">预测准确率</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.accuracy}%</div>
            <p className="text-xs text-muted-foreground">
              +2.1% 较上月
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Charts Section */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Trend Chart */}
        <Card>
          <CardHeader>
            <CardTitle>销售趋势对比</CardTitle>
            <CardDescription>实际销售额 vs 预测销售额（万元）</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={trendData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" />
                <YAxis />
                <Tooltip />
                <Line 
                  type="monotone" 
                  dataKey="sales" 
                  stroke="#3b82f6" 
                  strokeWidth={2}
                  name="实际销售额"
                />
                <Line 
                  type="monotone" 
                  dataKey="prediction" 
                  stroke="#10b981" 
                  strokeWidth={2}
                  strokeDasharray="5 5"
                  name="预测销售额"
                />
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Product Performance */}
        <Card>
          <CardHeader>
            <CardTitle>重点产品预测</CardTitle>
            <CardDescription>当前销售额 vs 预测销售额（万元）</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={productData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis />
                <Tooltip />
                <Bar dataKey="current" fill="#3b82f6" name="当前销售额" />
                <Bar dataKey="predicted" fill="#10b981" name="预测销售额" />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>

      {/* Recent Tasks */}
      <Card>
        <CardHeader>
          <CardTitle>最近任务</CardTitle>
          <CardDescription>系统最近执行的任务和状态</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {recentTasks.map((task) => (
              <div key={task.id} className="flex items-center justify-between p-4 border rounded-lg">
                <div className="flex items-center space-x-3">
                  {getStatusIcon(task.status)}
                  <div>
                    <p className="font-medium text-gray-900">{task.name}</p>
                    <p className="text-sm text-gray-500">{task.time}</p>
                  </div>
                </div>
                <div className="flex items-center space-x-3">
                  {getStatusBadge(task.status)}
                  <Button variant="ghost" size="sm">
                    查看详情
                  </Button>
                </div>
              </div>
            ))}
            {recentTasks.length === 0 && !loading && (
              <div className="text-center py-8 text-gray-500">
                暂无任务数据
              </div>
            )}
            {loading && (
              <div className="text-center py-8 text-gray-500">
                加载中...
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 演示模式提示弹窗 */}
      <DemoModeAlert 
        isOpen={showDemoAlert}
        onClose={() => setShowDemoAlert(false)}
        title="演示模式"
      />
    </div>
  )
}

